package com.qst.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qst.beans.*;
import com.qst.service.impl.OrderServiceImpl;
import com.qst.service.impl.ProductServiceImpl;
import com.qst.util.AlipayConfig;
//import org.apache.commons.collections.bag.SynchronizedSortedBag;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


@Controller
public class OrderController {

    @Autowired
    private OrderServiceImpl orderService;

    @Autowired
    private ProductServiceImpl productService;

    //添加订单到数据库
    @RequestMapping("/saveOrder")
    public String saveOrder( HttpServletRequest request){

        Cart sessionCart = (Cart)request.getSession().getAttribute("sessionCart");//获取购物车
        User enterUser = (User)request.getSession().getAttribute("enterUser");
        if (enterUser==null){
            return "views/login";
        }
        Order order = new Order();
        order.setOrdertime(new Date());//当前时间
        order.setStatu(1);//状态为未付款
        /*应该有第二备选地址与电话*/
        order.setName(enterUser.getUsername());
        order.setAddress(enterUser.getAddress());
        order.setPhone(enterUser.getPhone());

        for (CartItem ci: sessionCart.getCartItems()
             ) {
            OrderItem orderItem = new OrderItem();
            orderItem.setProduct(ci.getProduct());
            orderItem.setCount(ci.getCount());
            orderItem.setSubtotal(ci.getSubtotal());
            /*修改数据库中商品的热度*/
            Product product = productService.findById(ci.getProduct().getPid());
            product.setIs_hot(product.getIs_hot()+1);
            productService.update(product);

            //将订单项添加到订单中
            if (orderItem!=null) {
                order.getOrderItemSet().add(orderItem);
            }
            order.setTotal(order.getTotal()+ci.getSubtotal());
        }
        order.setUser(enterUser);
        //将订单添加到数据库，
        orderService.addItem(order);//将表单添加时，必定会添加表单项
        System.out.println("生成的订单："+order.getOrdertime()+":"+order.getUser());
        //提交订单后，清空购物车
//        Cart sessionCart = (Cart)request.getSession().getAttribute("seseionCart");
        sessionCart.clearCart();

        request.setAttribute("order",order);
        return "views/orders";
    }


    /*查询我的订单*/
    @RequestMapping("/myOrders")
    public String getMyOrders(Integer page, HttpServletRequest request){
        //分页查询用户所有订单
        User enterUser = (User)request.getSession().getAttribute("enterUser");
        PageUtils<Order> allOrders = null;
        if(page==null)
            page = 1;
        if (enterUser!=null) {
            allOrders = orderService.getAllOrdersByUid(page, enterUser.getId());
            System.out.println(enterUser.getUsername()+"的所有订单");
            for (Order order:allOrders.getList()
                 ) {
                System.out.println(order);
            }
        }
        request.setAttribute("allOrders",allOrders);
        return "views/myorders";
    }

    /*通过订单编号查找订单*/
    @RequestMapping("/findOrderByOid")
    public String findOrderByOid(@RequestParam("oid") Integer oid, HttpServletRequest request){
        Order order = orderService.findOrderByOid(oid);
        User enterUser = (User) request.getSession().getAttribute("enterUser");
        order.setUser(enterUser);
        System.out.println("编号:"+oid+"的订单");
        System.out.println(order);
        request.setAttribute("order",order);
        return "views/orders";
    }

    /*从订单中移除商品*/

    /*通过支付宝沙盒支付调用支付接口*/
    @RequestMapping(value = "/alipaydev")
    public void payInSandBox(Integer oid, HttpServletRequest request, HttpServletResponse response)throws Exception{

        Order order = orderService.findOrderByOid(oid);


        //获取初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);


        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
//        String out_trade_no = param.getTradeCode();
        String out_trade_no = order.getOid().toString();
                //付款金额，必填
//        String total_amount = param.getMoney().toString();
        String total_amount = String.valueOf(order.getTotal());
                //订单名称，必填
//        String subject = param.getSubject();
        String subject = String.valueOf(order.getOid());
                //商品描述，可空
//        String body = param.getRemark();
        String body = null;
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        /*order.setStatu(2);//修改订单状态为已付款
        orderService.updateOrder(order);*/

        response.setContentType("text/html;charset=" + AlipayConfig.charset);
        response.getWriter().write(result);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();

    }


    /**
     * 回调路径return_url
     * @param request
     * @param response
     */
    @RequestMapping("/return_url")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws Exception{
        System.out.println("修改订单状态信息");
        System.out.println("信息:"+request.getParameter("oid"));

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();

            String[] values = (String[]) requestParams.get(name);
            System.out.println("name:"+name+" value :"+values);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.sign_type);
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        Order order = orderService.findOrderByOid(Integer.parseInt(out_trade_no));
        order.setStatu(3);//修改订单状态为已支付，未收货
        orderService.updateOrder(order);
        System.out.println("系统订单："+ out_trade_no + "成功支付。");

        System.out.println("signVerified:"+signVerified);
        //里面取的金额应该修改
        if(signVerified) {
            //商户订单号
             out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("oid").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            request.setAttribute("out_trade_no", out_trade_no);
            request.setAttribute("trade_no", trade_no);
            request.setAttribute("total_amount", total_amount);


            System.out.println("订单处理：系统订单号" + out_trade_no + "支付宝交易号：" + trade_no);
            //系统处理根据支付宝回调更改订单状态或者其他关联表的数据
//            OrderInfo order = payService.findOneByTradeCode(out_trade_no);
//            Order order = orderService.findOrderByOid(Integer.parseInt(out_trade_no));
            if(order == null){
                signVerified = false;
                request.setAttribute("signVerified", signVerified);
                request.setAttribute("reason", "商户订单号不存在");
                System.out.println("系统订单："+ out_trade_no + "不存在。");
            }else{
                if(!String.valueOf(order.getTotal()).equals(total_amount)){
                    signVerified = false;
                    request.setAttribute("signVerified", signVerified);
                    request.setAttribute("reason", "付款金额不对");
                    return "alipay/notify_url";
                }


                if(order.getStatu() == 2){//判断当前订单是否已处理，避免重复处理
                    System.out.println("系统订单："+ out_trade_no + "无需重复处理。");
                }else{
                    System.out.println("修改订单状态....");
                    order.setStatu(2);//修改订单状态为已支付
                    Date payedAt = new Date();
//                    order.setTransactionId(trade_no);
//                    order.setPayedAt(payedAt);
                    //修改订单状态
//                    payService.payOrder(order);
                    orderService.updateOrder(order);
                    System.out.println("系统订单："+ out_trade_no + "成功支付。");
                }

            }
        }else{
            request.setAttribute("reason", "验签失败");
        }
        request.setAttribute("signVerified", signVerified);
        return "redirect: /myOrders";
    }

    @RequestMapping(value = "/toevaluation")
    public String toevaluation(@RequestParam("oid")Integer oid, HttpServletRequest request){
        /*获取订单中所有的订单项，然后在订单页面显示*/
        List<OrderItem> orderItemSet = orderService.findByOid(oid);
        request.setAttribute("orderItems",orderItemSet);
        return "views/evaluateItem";
    }


    /*评价某个表单项*/
    @RequestMapping(value = "/evluateOrderItem")
    @ResponseBody
    public String evluateOrderItem(@RequestBody OrderItem orderItem){
        System.out.println(orderItem);
        int b = orderService.updateOrderItem(orderItem);
        System.out.println("评价成功?"+b);
        if (b>0){
            Order order = orderService.findOrderByOid(orderItem.getOid());
            order.setStatu(4);
            return "ok";
        }
        return "no";
    }

    /*根据商品ID查询所有评价*/
    @RequestMapping(value = "/getAllPL")
    @ResponseBody
    public List<OrderItem> getAllPL(@RequestBody Product product){
        System.out.println("pid:"+product.getPid());
        List<OrderItem> orderItems = orderService.getOrderItemsByPid(product.getPid());
        List<OrderItem> orderItemList = new ArrayList<>();
        for (OrderItem orderItem:orderItems){
            System.out.println(orderItem);
            if((orderItem.getEvaluation()!=null&&orderItem.getEvaluation()!=" ")&&orderItem.getGwpj()!=null&&orderItem.getWlpj()!=null&&orderItem.getKfpj()!=null){
                orderItemList.add(orderItem);
            }
        }
        return orderItemList;
    }

    /*添加回复到商品评价中*/
    @RequestMapping(value = "addRespon")
    public void addResponseToOrderItem(@RequestBody OrderItem orderItem){
        System.out.println(orderItem);
        orderService.addResponseToOrderItem(orderItem);
    }

    //管理员发货
    /*@RequestMapping(value = "sendProduct")
    public void sendProduct(@PathVariable("oid") Integer oid){
         Order order = orderService.findOrderByOid(oid);
         order.setStatu(3);
         orderService.updateOrder(order);
    }*/

}
